import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import WebSocketService from '@/utils/WebSocket.js';
import { useRoomStore } from '@/stores/room';
import { useUserStore } from '@/stores/user';
import {computed, onMounted} from "vue";
import config from "@/config.js";
import {getGameById} from "@/api/game.js";

export const useRoom = () => {
    const router = useRouter();
    const route = useRoute();
    const roomStore = useRoomStore();
    const userStore = useUserStore();

    const wsUrl = config.apiWsUrl +'/ws/gameRoom';
    const webSocketService = new WebSocketService(wsUrl);
    const gameId = route.params.gameId;

    onMounted(() => {
        webSocketService.connect().then(() => {
            console.log('WebSocket连接已建立');
        }).catch((error) => {
            console.error('WebSocket连接失败:', error);
        });

        webSocketService.on('open', () => {
            console.log('WebSocket连接已建立');
        });

        webSocketService.on('message', handleMessage);
        webSocketService.on('close', () => {
            console.log('WebSocket连接已关闭');
            roomStore.clearRoomData();
        });

        webSocketService.on('error', (error) => {
            console.error('WebSocket发生错误:', error);
        });
    });

    const handleMessage = (data) => {
        console.log('handleMessage:', data.type, data);
        try {
            switch (data.type) {
                case 'roomUpdate':
                    // 完整房间数据更新
                    roomStore.updateRoomData({
                        roomId: data.roomId,
                        playerList: data.playerList || [],
                        hostId: data.hostId
                    });
                    break;

                case 'roomCreated':
                    // 创建成功只需要设置 roomId 并刷新
                    roomStore.roomId = data.roomId;
                    router.push(`/gameRoom/${gameId}/${data.roomId}`);
                    refreshRoom(data.roomId);
                    localStorage.setItem('currentRoomId', data.roomId);
                    break;

                case 'roomJoined':
                    // 加入成功只需要设置 roomId 并刷新
                    roomStore.roomId = data.roomId;
                    router.push(`/gameRoom/${gameId}/${data.roomId}`);
                    refreshRoom(data.roomId);
                    localStorage.setItem('currentRoomId', data.roomId);
                    break;

                case 'playerLeft':
                    ElMessage.warning(`玩家已离开房间`);
                    break;

                case 'roomDisbanded':
                    ElMessage.warning('房间已解散');
                    roomStore.clearRoomData();
                    router.push('/home');
                    break;
                case 'gameStarted':
                    ElMessage.success('游戏开始');
                    getGameById(data.gameId).then((response) => {
                        router.push('/'+response.path);
                    })
                    break;
                case 'error':
                    ElMessage.error(data.message || '操作失败');
                    roomStore.isLoading = false;
                    break;

                default:
                    console.warn('未知消息类型:', data.type);
            }
        } catch (e) {
            console.error('消息处理失败:', e);
            roomStore.isLoading = false;
        }
    };

    const refreshRoom = (id) => {
        console.log('刷新房间数据');
        roomStore.roomId = id;
        webSocketService.send({
            type: 'getRoom',
            roomId: id
        });
        getGameById(gameId).then((response) => {
            console.log('游戏信息:', response.data);
            roomStore.maxPlayers = response.maxPlayer;
            roomStore.minPlayers = response.minPlayer;
            roomStore.gameName = response.name;
        })
    };

    const createRoom = (roomId) => {
        roomStore.isLoading = true;
        webSocketService.send({
            type: 'createRoom',
            roomId,
            userId: userStore.userId
        });
        getGameById(gameId).then((response) => {
            console.log('游戏信息:', response.data);
            roomStore.maxPlayers = response.maxPlayer;
            roomStore.minPlayers = response.minPlayer;
            roomStore.gameName = response.name;
        })


    };

    const joinRoom = (roomId) => {
        roomStore.isLoading = true;
        webSocketService.send({
            type: 'joinRoom',
            roomId,
            userId: userStore.userId
        });
    };

    const startGame = () => {
        router.push(`/gameRoom/${gameId}`);
        webSocketService.send({
            type: 'startGame',
            roomId: roomStore.roomId,
            userId: userStore.userId,
            gameId: gameId
        });
    };

    const leaveRoom = () => {
        webSocketService.send({
            type: 'leaveRoom',
            roomId: roomStore.roomId,
            userId: userStore.userId
        });
        roomStore.clearRoomData();
        router.push('/home');
    };

    return {
        roomId: computed(() => roomStore.roomId),
        players: computed(() => roomStore.players),
        maxPlayers: computed(() => roomStore.maxPlayers),
        minPlayers: computed(() => roomStore.minPlayers),
        hostId: computed(() => roomStore.hostId),
        isLoading: computed(() => roomStore.isLoading),
        isHost: computed(() => roomStore.isHost),
        roomStatus: computed(() => roomStore.roomStatus),
        startGame,
        leaveRoom,
        refreshRoom,
        createRoom,
        joinRoom
    };
};
